package com.ruoyi.common.utils.miniprogram;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
public class WxAccessTokenUtils {

    private static String appId;
    private static String appSecret;

    @Value("${miniprogram.appId}")
    public void setAppId(String appId) {
        WxAccessTokenUtils.appId = appId;
    }

    @Value("${miniprogram.appSecret}")
    public void setAppSecret(String appSecret) {
        WxAccessTokenUtils.appSecret = appSecret;
    }

    /**
     * 获取小程序全局唯一后台接口调用凭据，token有效期为7200s，开发者需要进行妥善保存。
     *
     * @return
     */
    public static String getWxAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        HttpRequest httpRequest = HttpUtil.createGet(url);
        UrlBuilder urlBuilder = UrlBuilder.of(url);
        urlBuilder.addQuery("grant_type", "client_credential");
        urlBuilder.addQuery("appid", appId);
        urlBuilder.addQuery("secret", appSecret);
        httpRequest.setUrl(urlBuilder);
//        log.info("getWxAccessToken httpRequest: {}", httpRequest);
        String result = httpRequest.execute().body();

//        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);
//        String result = HttpUtils.sendGet(url);
        //输出示例：getWxAccessToken result: {"access_token":"71_2G94kKMeNIeSKiDkGrbAYSGvRcMediWNSK7KjnI7gMv0WerV3vW9hDYESD1s45h5vh2I3eWC_L7Yk4nt8eN2RSyMcXG4zkR0TcuZo_pS7r-jGiPNTi1v468p4qQQVNgADAJOG","expires_in":7200}
        log.info("getWxAccessToken result: {}", result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (Objects.isNull(jsonObject)) return null;
        return jsonObject.getString("access_token");
    }

}
